import {localUitl} from './localUitl';

const postMessageUtil = {};

window.addEventListener("message", (res) => {
  let obj = res.data;
  if (typeof obj == "string") {
    if (obj.indexOf("webpack") != -1) return;
    obj = JSON.parse(obj);
  }
  let action = obj.action;//收到的action指令
  let data = obj.data;//收到的消息数据
  if (!action) {
    return;
  }
  let token = localUitl.getToken();
  switch (action) {
    case "token":
      let iframeDom = document.getElementById("ifr");
      postMessageUtil.postMessage(iframeDom, "token", {"access_token": token});
      break;
    case "accesstoken":
      postMessageUtil.postMessageSelf(res, "accesstoken", {"access_token": token});
      break;
  }
})

postMessageUtil.postMessage = function (iframeDom, action, data) {
  iframeDom.contentWindow.postMessage(JSON.stringify({action, data}), "*");
}

postMessageUtil.postMessageSelf = function (event, action, data) {
  event.source.postMessage(JSON.stringify({action, data}), "*");
}
